package com.synnex.mobile.servier.web.notification.controller.admin;

import com.synnex.mobile.generic.core.exception.SystemException;
import com.synnex.mobile.generic.core.util.MultiValueMap;
import com.synnex.mobile.generic.log.dao.annotation.LogClass;
import com.synnex.mobile.generic.log.dao.annotation.LogMethod;
import com.synnex.mobile.generic.web.anotation.mapping.RequestMapping;
import com.synnex.mobile.generic.web.view.ModelAndView;
import com.synnex.mobile.generic.web.view.RedirectView;
import com.synnex.mobile.servier.core.notification.bo.DeviceTokenBo;
import com.synnex.mobile.servier.core.notification.bo.NotificationBo;
import com.synnex.mobile.servier.web.notification.controller.AbstractNotifyController;
import com.synnex.mobile.servier.web.notification.form.NotificationForm;
import com.synnex.mobile.servier.web.utils.DateUtil;
import com.synnex.mobile.servier.web.utils.IOSPushMsgUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author kerryf
 */
@RequestMapping(url = "/admin")
@LogClass(name = "admin notification")
public class AdminNotifyController extends AbstractNotifyController {


    @RequestMapping(url = "/listNotification.do")
    @LogMethod(name = "mobile get notification list")
    public ModelAndView getNotificationList(HttpServletRequest request, HttpServletResponse response) {
        try {
            String downLoadLink = "http://"+this.getConfig().getFtpHost()+this.getConfig().getFtpDownLoadPath()+"/";
            Map<String,Object> model = super.getNotifications(request,"admin");
            model.put("link",downLoadLink);
            return new ModelAndView(model);
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }


    @RequestMapping(url="/addNotification.do")
    @LogMethod(name="jump to notification page")
    public ModelAndView addNotification(HttpServletRequest request,HttpServletResponse response){

            return new ModelAndView();
    }

    @RequestMapping(url="/addNotifyAction.do",formCommand = "addNotification")
    @LogMethod(name="add notification")
    public ModelAndView addNotificationAction(HttpServletRequest request,HttpServletResponse response,NotificationForm form){
        String msg = request.getParameter("msg");
        String title = request.getParameter("title");
        String sendNow = request.getParameter("sendNow");
        try{
            NotificationBo bo = new NotificationBo();
            bo.setMsg(msg);
            bo.setTitle(title);

            bo.setPlanSendTime(DateUtil.strToDate(form.getPlanSendTime(),"yyyy-MM-dd HH:mm:ss"));

            MultiValueMap url = uploadFilesToFtp(request, "fileName", null);
            if (null != url.get("fileName")) {
                String name = url.get("fileName").toString();
                bo.setPicPath(name.substring(1, name.length() - 1));
            }

            if("Y".equals(sendNow)){
                bo.setActualSendTime(new Date());
                bo.setSendNow("Y");
            }else{
                bo.setSendNow("N");
            }

            Integer id = notificationService.addNotification(bo);
            String link = "http://"+this.getConfig().getFtpHost()+this.getConfig().getFtpDownLoadPath()+"/";
            String iconPath="";
            if(bo.getPicPath()!=null && !bo.getPicPath().equals("")){
                iconPath = bo.getPicPath();
            }

            StringBuilder    message = new StringBuilder("{'aps':{");
            message.append("'alert':'").append(bo.getTitle()).append("',")
              .append("'icon':'").append(iconPath).append("',")
              .append("'id':'").append(id) .append("'") ;

            message.append("}}");

            byte[] buff=message.toString().getBytes();
            int f=buff.length;
            System.out.println("------------message byte sizes: "+f);

            if("Y".equals(sendNow)){

                List<DeviceTokenBo> tokenObjs = tokenService.getDeviceToken();
                List<String> tokens = new ArrayList<String>();
                if(null != tokenObjs && !tokenObjs.isEmpty()){
                    for(DeviceTokenBo tokenBo: tokenObjs){
                        tokens.add(tokenBo.getToken());
                    }
                    new SendNotification(message.toString(),tokens,true).start();
//                    new SendNotification(message.toString(),tokens,false).start();

                }
            }

            return new ModelAndView(new RedirectView("/admin/listNotification.do"));
        }catch (Exception e){
            throw  new SystemException(e);
        }
    }

    @RequestMapping(url="/delNotification.do")
    @LogMethod(name="delete notification")
    public ModelAndView delNotification(HttpServletRequest request,HttpServletResponse response){

        String id = request.getParameter("id");
        notificationService.deleteNotify(Integer.parseInt(id));
        return new ModelAndView(new RedirectView("/admin/listNotification.do"));
    }


//    private List<String> sendNotification(String msg,List<String> tokens){
//
//        if(null != tokens && !tokens.isEmpty()){
//            IOSPushMsgUtil iosPush = new IOSPushMsgUtil();
//            tokens = iosPush.sendPush(tokens, "Certificates.servier.p12","synnex",msg,1,true);
////            tokens = iosPush.sendPush(tokens, "promocentralPNSCer_iPhone.p12","synnex",msg,1,true);
//            return tokens;
//        }else{
//            return null;
//        }
//    }

    class SendNotification extends Thread {

        private String msg;
        private List<String> tokens;
        private boolean isProd;

        public SendNotification() {
        }
        public SendNotification(String msg, List<String> tokens,boolean  isProd) {
            super();
            this.msg = msg;
            this.tokens = tokens;
            this.isProd = isProd;
        }

        public void run() {
            if(null != tokens && !tokens.isEmpty()){
                IOSPushMsgUtil iosPush = new IOSPushMsgUtil();
                tokens = iosPush.sendPush(tokens, "Certificates.servier.p12","synnex",msg,1,isProd);
//            tokens = iosPush.sendPush(tokens, "promocentralPNSCer_iPhone.p12","synnex",msg,1,true);
            }
        }
    }


}
